package cn.lili.controller.feign;

import cn.hutool.core.collection.CollectionUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.utils.StringUtils;
import cn.lili.modules.constant.CommonConstant;
import cn.lili.modules.distribution.client.DistributionClient;
import cn.lili.modules.distribution.entity.dos.Distribution;
import cn.lili.modules.distribution.entity.dto.DistributionQueryDTO;
import cn.lili.modules.distribution.entity.enums.DistributionStatusEnum;
import cn.lili.modules.distribution.entity.vos.DistributionVO;
import cn.lili.modules.distribution.service.DistributionService;
import cn.lili.modules.member.entity.dos.UnionMember;
import cn.lili.modules.member.entity.vo.NumberOfOwnersReq;
import cn.lili.modules.order.order.client.RankingDistributionClient;
import cn.lili.modules.order.order.entity.dos.RankingDistribution;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequiredArgsConstructor
public class DistributionFeignController implements DistributionClient {

    @Getter
    private final DistributionService distributionService;
    private final RankingDistributionClient rankingDistributionClient;

    @Override
    public void updateDistributionAmount() {
        distributionService.updateDistributionAmount();
    }

    @Override
    public Distribution getDistribution(String userId) {
        Distribution one = distributionService.getOne(new LambdaQueryWrapper<Distribution>().eq(Distribution::getMemberId, userId).orderByDesc(Distribution::getCreateTime).last("limit 1"));
        return one;
    }

    @Override
    public Distribution getDistributionPass(String userId) {
        LambdaQueryWrapper<Distribution> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Distribution::getMemberId, userId);
        lambdaQueryWrapper.eq(Distribution::getDistributionStatus, DistributionStatusEnum.PASS.name());
        lambdaQueryWrapper.last("limit 1");
        return distributionService.getOne(lambdaQueryWrapper);
    }


    @Override
    public Distribution getDistributionById(String id) {
        Distribution one = distributionService.getOne(new LambdaQueryWrapper<Distribution>().eq(Distribution::getId, id));
        return one;
    }

    /**
     * 添加总佣金积分
     *
     * @param scoreScale 添加金额
     */
    @Override
    public void addGrossCommission(String id, BigDecimal scoreScale) {
        Distribution distribution = distributionService.getById(id);
        if (distribution == null) {
            log.error("未获取到分销员信息 ： {}", id);
            return;
        }
        if (distribution.getGrossCommission() != null) {
            distribution.setGrossCommission(distribution.getGrossCommission().add(scoreScale));
        } else {
            distribution.setGrossCommission(scoreScale);
        }
        distributionService.updateById(distribution);
    }


    /**
     * 减少总佣金积分
     *
     * @param scoreScale 减少金额
     */
    @Override
    public void subtractCommission(String id, BigDecimal scoreScale) {
        Distribution distribution = distributionService.getById(id);
        if (distribution == null) {
            log.error("未获取到分销员信息 ： {}", id);
            return;
        }
        distribution.setGrossCommission(distribution.getGrossCommission().subtract(scoreScale));
        distributionService.updateById(distribution);
    }

    /**
     * 添加总佣金积分
     *
     * @param scoreScale 添加金额
     */
    @Override
    public void addRebateTotal(String id, BigDecimal scoreScale) {
        Distribution distribution = distributionService.getById(id);
        if (distribution == null) {
            log.error("未获取到分销员信息 ： {}", id);
            return;
        }
        if (distribution.getRebateTotal() != null) {
            distribution.setRebateTotal(distribution.getGrossCommission().add(scoreScale).doubleValue());
        } else {
            distribution.setRebateTotal(scoreScale.doubleValue());
        }
        distributionService.updateById(distribution);
    }

    /**
     * 添加直推数量
     */
    @Override
    public void addDirectOrderNumber(String id) {
        Distribution distribution = distributionService.getById(id);
        if (distribution == null) {
            log.error("未获取到分销员信息 ： {}", id);
            return;
        }
        if (distribution.getDirectOrderNumber() != null) {
            distribution.setDirectOrderNumber(distribution.getDirectOrderNumber() + 1);
        } else {
            distribution.setDirectOrderNumber(1);
        }
        distributionService.updateById(distribution);
    }


    @Override
    public List<Distribution> getDistributionList(Distribution dis) {
        LambdaQueryWrapper<Distribution> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(dis.getDistributionStatus())) {
            query.eq(Distribution::getDistributionStatus, dis.getDistributionStatus());
        }
        query.eq(Distribution::getDeleteFlag, Boolean.FALSE);
        return distributionService.list(query);
    }

    /**
     * 更新店主邀请人信息
     *
     * @param dis
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateDistributionParentInfo(Distribution dis) {
        LambdaUpdateWrapper<Distribution> query = new LambdaUpdateWrapper<>();
        query.eq(Distribution::getMemberId, dis.getMemberId());
        query.eq(Distribution::getDistributionStatus, DistributionStatusEnum.PASS.name());
        query.set(Distribution::getParentId, dis.getParentId());
        query.set(Distribution::getParentUsername, dis.getParentUsername());
        boolean update = distributionService.update(query);
        if (update) {
            RankingDistribution rankingDis = new RankingDistribution();
            rankingDis.setMemberId(dis.getMemberId());
            rankingDis.setParentId(dis.getParentId());
            rankingDis.setParentFyName(dis.getParentUsername());
            rankingDistributionClient.updateRankingDistribution(rankingDis);
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean clearParentInfo(Distribution dis) {
        log.info("clearParentInfo == dis == {}", JSONObject.toJSONString(dis));
        //清空分销员表上级
        LambdaUpdateWrapper<Distribution> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Distribution::getMemberId, dis.getMemberId());
        updateWrapper.eq(Distribution::getDistributionStatus, DistributionStatusEnum.PASS.name());
        updateWrapper.set(Distribution::getParentId, null);
        updateWrapper.set(Distribution::getParentUsername, null);
        boolean update = distributionService.update(updateWrapper);
        //清空店主表上级
        Boolean b = rankingDistributionClient.clearParentInfo(dis);
        log.info("update= {}, b = {}", update, b);
        return true;
    }

    /**
     * 用户类型
     *
     * @param userIdList 用户列表
     * @return
     */
    @Override
    public Map<String, Integer> computeType(List<String> userIdList) {
        Map<String, Integer> result = new HashMap<>();
        for (String id : userIdList) {
            //默认设置成会员类型
            result.put(id, 1);
        }
        List<Distribution> distributionList = distributionService.list(new LambdaQueryWrapper<Distribution>()
                .eq(Distribution::getDistributionStatus, DistributionStatusEnum.PASS.name())
                .in(Distribution::getMemberId, userIdList));
        if (CollectionUtil.isNotEmpty(distributionList)) {
            for (Distribution distribution : distributionList) {
                for (String id : userIdList) {
                    if (distribution.getMemberId().equals(id)) {
                        //设置成店主类型
                        result.put(id, 2);
                    }
                }
            }
        }
        return result;
    }


    @Override
    public Double getLowerAndLowerComissSubByParentId(DistributionQueryDTO dto) {
        distributionService.selectDisLowerAndLowerSubComissByParentId(dto.getParentId(), null, null);
        return null;
    }


    @Override
    public List<Distribution> getListByName(String keyword) {
        return distributionService.getListByName(keyword);
    }

//    @Override
//    public IPage<Distribution> getPage(DistributionVO distributionVO) {
//        LambdaQueryWrapper<Distribution> queryWrapper = new LambdaQueryWrapper<>();
//        if (StringUtils.isNotEmpty(distributionVO.getId())) {
//            queryWrapper.eq(Distribution::getId, distributionVO.getId());
//        }
//        if (StringUtils.isNotEmpty(distributionVO.getMemberName())) {
//            queryWrapper.like(Distribution::getMemberName, distributionVO.getMemberName());
//        }
//        if (StringUtils.isNotEmpty(distributionVO.getUnionName())) {
//            queryWrapper.like(Distribution::getMemberName, distributionVO.getMemberName());
//        }
//        Page<Distribution> distributionPage = distributionService.page(new Page<>(distributionVO.getPageNumber(), distributionVO.getPageSize()), queryWrapper);
//        return distributionPage;
//    }

    @Override
    public List<Distribution> getList(DistributionVO distributionVO) {
        LambdaQueryWrapper<Distribution> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(distributionVO.getId())) {
            queryWrapper.eq(Distribution::getId, distributionVO.getId());
        }
        if (StringUtils.isNotEmpty(distributionVO.getMemberName())) {
            queryWrapper.like(Distribution::getMemberName, distributionVO.getMemberName());
        }
        if (StringUtils.isNotEmpty(distributionVO.getUnionName())) {
            queryWrapper.like(Distribution::getMemberName, distributionVO.getMemberName());
        }
        queryWrapper.last(" limit " + (distributionVO.getPageNumber() - 1 ) * distributionVO.getPageSize() + "," + distributionVO.getPageSize());
        List<Distribution> distributionPage = distributionService.list(queryWrapper);
        return distributionPage;
    }

    @Override
    public List<Distribution> getListByDistribution(DistributionVO distributionVO) {
        LambdaQueryWrapper<Distribution> queryWrapper = distributionService.createQueryWrapper(distributionVO);
        return distributionService.list(queryWrapper);
    }

    @Override
    public Long getCountByTypeWrapper(Integer type) {
        LambdaQueryWrapper<Distribution> queryWrapper = distributionService.createQueryWrapper(new DistributionVO());
        if (queryWrapper == null) {
            return 0L;
        }
        if (type != null) {
            // 1. 今日
            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_01)) {
                queryWrapper.apply("TO_DAYS(audit_time) = TO_DAYS(NOW())");
            }
            // 2. 昨日
            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_02)) {
                queryWrapper.apply("TO_DAYS(audit_time) = TO_DAYS(NOW() - INTERVAL 1 DAY)");
            }
            // 3. 本周
            LocalDate firstDayOfWeek = LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
            LocalDate lastDayOfWeek = LocalDate.now().with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_03)) {
                queryWrapper.between(Distribution::getAuditTime, firstDayOfWeek, lastDayOfWeek);
            }
            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_04)) {
                // 4. 上周
                LocalDate firstDayOfLastWeek = firstDayOfWeek.minusDays(7);
                LocalDate lastDayOfLastWeek = lastDayOfWeek.minusDays(7);
                queryWrapper.between(Distribution::getAuditTime, firstDayOfLastWeek, lastDayOfLastWeek);
            }
            // 5. 本月
            LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
            LocalDate lastDayOfMonth = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_05)) {
                queryWrapper.between(Distribution::getAuditTime, firstDayOfMonth, lastDayOfMonth);
            }
            // 6. 上月
            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_06)) {
                LocalDate firstDayOfLastMonth = firstDayOfMonth.minusMonths(1);
                LocalDate lastDayOfLastMonth = lastDayOfMonth.minusMonths(1);
                queryWrapper.between(Distribution::getAuditTime, firstDayOfLastMonth, lastDayOfLastMonth);
            }
            // 7. 本季度
            LocalDate now = LocalDate.now();
            LocalDate firstDayOfQuarter = now.with(now.getMonth().firstMonthOfQuarter()).with(TemporalAdjusters.firstDayOfMonth());
            LocalDate lastDayOfQuarter = firstDayOfQuarter.plusMonths(2).with(TemporalAdjusters.lastDayOfMonth());
            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_07)) {
                queryWrapper.between(Distribution::getAuditTime, firstDayOfQuarter, lastDayOfQuarter);
            }
            // 8. 上季度
            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_08)) {
                LocalDate firstDayOfLastQuarter = firstDayOfQuarter.minusMonths(3);
                LocalDate lastDayOfLastQuarter = firstDayOfQuarter.minusDays(1);
                queryWrapper.between(Distribution::getAuditTime, firstDayOfLastQuarter, lastDayOfLastQuarter);
            }
            // 9. 今年
            LocalDate firstDayOfYear = LocalDate.now().with(TemporalAdjusters.firstDayOfYear());
            LocalDate lastDayOfYear = LocalDate.now().with(TemporalAdjusters.lastDayOfYear());
            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_09)) {
                queryWrapper.between(Distribution::getAuditTime, firstDayOfYear, lastDayOfYear);
            }
            // 10. 去年
            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_10)) {
                LocalDate firstDayOfLastYear = firstDayOfYear.minusYears(1);
                LocalDate lastDayOfLastYear = lastDayOfYear.minusYears(1);
                queryWrapper.between(Distribution::getAuditTime, firstDayOfLastYear, lastDayOfLastYear);
            }
        }
        return distributionService.count(queryWrapper);
    }

    @Override
    public Long getCountByWrapper() {
//        LambdaQueryWrapper<Distribution> queryWrapper = numberOfOwnersReq.getMemberLambdaQueryWrapper();
        LambdaQueryWrapper<Distribution> queryWrapper = distributionService.createQueryWrapper(new DistributionVO());
//        Integer type = numberOfOwnersReq.getType();
        if (queryWrapper == null) {
            return 0L;
        }
//        if (numberOfOwnersReq.getType() != null) {
//            // 1. 今日
//            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_01)) {
//                queryWrapper.apply("TO_DAYS(create_time) = TO_DAYS(NOW())");
//            }
//            // 2. 昨日
//            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_02)) {
//                queryWrapper.apply("TO_DAYS(create_time) = TO_DAYS(NOW() - INTERVAL 1 DAY)");
//            }
//            // 3. 本周
//            LocalDate firstDayOfWeek = LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
//            LocalDate lastDayOfWeek = LocalDate.now().with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
//            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_03)) {
//                queryWrapper.between(Distribution::getCreateTime, firstDayOfWeek, lastDayOfWeek);
//            }
//            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_04)) {
//                // 4. 上周
//                LocalDate firstDayOfLastWeek = firstDayOfWeek.minusDays(7);
//                LocalDate lastDayOfLastWeek = lastDayOfWeek.minusDays(7);
//                queryWrapper.between(Distribution::getCreateTime, firstDayOfLastWeek, lastDayOfLastWeek);
//            }
//            // 5. 本月
//            LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
//            LocalDate lastDayOfMonth = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
//            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_05)) {
//                queryWrapper.between(Distribution::getCreateTime, firstDayOfMonth, lastDayOfMonth);
//            }
//            // 6. 上月
//            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_06)) {
//                LocalDate firstDayOfLastMonth = firstDayOfMonth.minusMonths(1);
//                LocalDate lastDayOfLastMonth = lastDayOfMonth.minusMonths(1);
//                queryWrapper.between(Distribution::getCreateTime, firstDayOfLastMonth, lastDayOfLastMonth);
//            }
//            // 7. 本季度
//            LocalDate now = LocalDate.now();
//            LocalDate firstDayOfQuarter = now.with(now.getMonth().firstMonthOfQuarter()).with(TemporalAdjusters.firstDayOfMonth());
//            LocalDate lastDayOfQuarter = firstDayOfQuarter.plusMonths(2).with(TemporalAdjusters.lastDayOfMonth());
//            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_07)) {
//                queryWrapper.between(Distribution::getCreateTime, firstDayOfQuarter, lastDayOfQuarter);
//            }
//            // 8. 上季度
//            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_08)) {
//                LocalDate firstDayOfLastQuarter = firstDayOfQuarter.minusMonths(3);
//                LocalDate lastDayOfLastQuarter = firstDayOfQuarter.minusDays(1);
//                queryWrapper.between(Distribution::getCreateTime, firstDayOfLastQuarter, lastDayOfLastQuarter);
//            }
//            // 9. 今年
//            LocalDate firstDayOfYear = LocalDate.now().with(TemporalAdjusters.firstDayOfYear());
//            LocalDate lastDayOfYear = LocalDate.now().with(TemporalAdjusters.lastDayOfYear());
//            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_09)) {
//                queryWrapper.between(Distribution::getCreateTime, firstDayOfYear, lastDayOfYear);
//            }
//            // 10. 去年
//            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_10)) {
//                LocalDate firstDayOfLastYear = firstDayOfYear.minusYears(1);
//                LocalDate lastDayOfLastYear = lastDayOfYear.minusYears(1);
//                queryWrapper.between(Distribution::getCreateTime, firstDayOfLastYear, lastDayOfLastYear);
//            }
//        }
        return distributionService.count(queryWrapper);
    }
}
